package com.yr.visa.connection;

import java.util.Set;

import org.apache.http.cookie.Cookie;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.yr.visa.httpclient.HttpsAction;
import com.yr.visa.httpclient.Request;
import com.yr.visa.httpclient.Response;
import com.yr.visa.httpclient.Site;
import com.yr.visa.proxy.LoginProxy;
import com.yr.visa.proxy.ctx.Brower;

@Component
public class ConnectionInvoker {

	@Autowired
	ConfigManager configManager;
	@Autowired
	private LoginProxy proxy;
	
	private Brower loginBrower;
	
	private Site site = new Site("online.immi.gov.au") ;
	
	private Object lock= new Object();
	
	public void login(){
		synchronized (lock) {
			if(loginBrower == null || !checkIsLogin()){
				this.loginBrower.getDriver().quit();
				this.loginBrower = proxy.login();
			}
		}
	}
	
	
	private boolean checkIsLogin(){
		
		Request r = new Request("https://online.immi.gov.au/elp/app?action=new&formId=VSS-AP-600");
		r.addCookie(transferCookie(this.loginBrower.getCookie()));
		r.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
		r.addHeader("Accept-Encoding", "gzip, deflate, sdch, br");
		Response response =HttpsAction.getInstance().doRequest(r, site);
		if(response.getStatusCode()==302 && response.getExtendsions().contains("login")){
			return false;
		}
		return true;
		
	}
	
	private Cookie[] transferCookie(Set<org.openqa.selenium.Cookie> originCookie){
		if(originCookie == null){
			return new Cookie[0];
		}
		Cookie[] cs = new Cookie[originCookie.size()];
		int i=0;
		for(org.openqa.selenium.Cookie oc :originCookie ){
			Cookie c = new BasicClientCookie(oc.getName(), oc.getValue());
			cs [i] =c;
			i++;
		}
		return cs;
	}
}
